import { useLocalStorage } from "@/hooks/useLocalStorage"
import { RootState } from "@/store"
import { RouteMeta, RouteRecordRaw } from "vue-router"
import { Module } from "vuex"
import { cameraManagement } from "./CameraManagement"
import { userManagement } from "./UserManagement"
import { fileManagement } from "./FileManagement"
import { websiteManagement } from "./WebsiteManagement"
import { IAdminActions, IAdminGetter, IAdminMenu, IAdminMutations, IAdminState } from "./types"
import { getState, setState } from "@/utils/core"

const state: IAdminState = {
    menuRoutes: [],
    isCollapse: false
}

const actions: IAdminActions = {
    generateMenuRoutes({ commit }, routes: RouteRecordRaw[]) {
        const adminMenuRoutes = routes.filter(r => r.meta.parentPath === "/admin")
        commit("_generateMenuRoutes", composeMenu(adminMenuRoutes))
        return true
    },
    getState({ state }, path: string) {
        return getState(state, path)
    },
}
function composeMenu(routes: RouteRecordRaw[]) {
    const tempRoutes = [];
    let obj = {} as IAdminMenu;
    routes.forEach(r => {
        const meta: RouteMeta = r.meta
        obj.path = r.path;
        Object.keys(meta).forEach(key => obj[key] = meta[key]);
        if (r.children?.length) {
            obj.children = composeMenu(r.children)
        }
        tempRoutes.push(obj);
        obj = {}
    })
    return tempRoutes;
}

const mutations: IAdminMutations = {
    _setState: (state: IAdminState, { path, value }) => {
        setState(state, path, value);
        console.log(state.isCollapse);

    },
    _generateMenuRoutes(state: IAdminState, payload: RouteRecordRaw[]) {
        state.menuRoutes = payload;
        useLocalStorage().setLocalStorage("menuRoutes", payload)

    },
}
const getters: IAdminGetter = {}

export const admin: Module<IAdminState, RootState> = {
    namespaced: true,
    state,
    actions,
    mutations,
    getters,
    modules: {
        userManagement,
        websiteManagement,
        cameraManagement,
        fileManagement
    }
}
